package com.djf.djfcs.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.djf.djfcs.dto.OrderDetailResponse;
import com.djf.djfcs.dto.OrderQueryRequest;
import com.djf.djfcs.service.OrderQueryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 订单查询控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/order")
@RequiredArgsConstructor
@Api(tags = "订单查询接口")
public class OrderQueryController {

    private final OrderQueryService orderQueryService;

    /**
     * 根据用户ID和时间范围查询订单详情和配送详情
     */
    @PostMapping("/query")
    @ApiOperation("查询用户订单详情")
    public ResponseEntity<Page<OrderDetailResponse>> queryOrderDetails(
            @Validated @RequestBody OrderQueryRequest request) {
        
        log.info("接收到订单查询请求: {}", request);
        
        try {
            Page<OrderDetailResponse> result = orderQueryService.queryOrderDetails(request);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询订单详情失败", e);
            throw new RuntimeException("查询订单详情失败: " + e.getMessage());
        }
    }

    /**
     * GET方式查询订单详情（便于测试）
     */
    @GetMapping("/query")
    @ApiOperation("查询用户订单详情（GET方式）")
    public ResponseEntity<Page<OrderDetailResponse>> queryOrderDetailsGet(
            @RequestParam Long userId,
            @RequestParam String startTime,
            @RequestParam String endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        log.info("接收到订单查询请求 - 用户ID: {}, 时间范围: {} - {}", userId, startTime, endTime);
        
        try {
            OrderQueryRequest request = new OrderQueryRequest();
            request.setUserId(userId);
            request.setStartTime(java.time.LocalDateTime.parse(startTime.replace(" ", "T")));
            request.setEndTime(java.time.LocalDateTime.parse(endTime.replace(" ", "T")));
            request.setPageNum(pageNum);
            request.setPageSize(pageSize);
            
            Page<OrderDetailResponse> result = orderQueryService.queryOrderDetails(request);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询订单详情失败", e);
            throw new RuntimeException("查询订单详情失败: " + e.getMessage());
        }
    }
}